package com.jiashihui.server1.utils;

/**
 * @describe: unicode transform
 *
 * @author jiashihui
 * @date 2018/11/30
 */
public class UnicodeTransUtil {

    /**
     * @author: jiashihui
     * @description 编码
     * @date: 2018/11/30 15:40
     * @param source
     * @return 
     */
    public static String unicode(String source){
        StringBuffer sb = new StringBuffer();
        char [] source_char = source.toCharArray();
        String unicode = null;
        for (int i=0;i<source_char.length;i++) {
            unicode = Integer.toHexString(source_char[i]);
            if (unicode.length() <= 2) {
                unicode = "00" + unicode;
            }
            sb.append("\\u" + unicode);
        }
        return sb.toString();
    }

    /**
     * @author: jiashihui
     * @description 解码
     * @date: 2018/11/30 15:40
     * @param unicode
     * @return 
     */
    public static String decodeUnicode(String unicode) {
        StringBuffer sb = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);
            sb.append((char) data);
        }
        return sb.toString();
    }

    /**
     * @author: jiashihui
     * @description 解码
     * @date: 2018/11/30 15:41
     * @param unicode
     * @return 
     */
    public static String decodeUnicode2(String unicode) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = unicode.indexOf("\\u", start + 2);
            String charStr = null;
            if (end == -1) {
                charStr = unicode.substring(start + 2, unicode.length());
            } else {
                charStr = unicode.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16);
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

}
